package com.example.pufang.controller;

import com.example.common.CommonResult;
import com.example.utils.PufangUtils;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.sql.Wrapper;
import java.util.*;

@RestController
@RequestMapping("/file")
@CrossOrigin
@Api(tags = "web用户文件上传接口")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    /**
     * 本地保存路径
     */
    @Value("${file.path}")
    private String dirPath;

    @RequestMapping(value = "/imgUpload")
    public CommonResult<Map<String, Object>> imgUpload(HttpServletRequest req, MultipartHttpServletRequest multiReq)
            throws IOException {

        HashMap<String, Object> map = new HashMap<>();

        // 获取当前系统时间，按照日期存储文件
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        String folderPath = calendar.get(Calendar.YEAR) + "/"
                + ( calendar.get(Calendar.MONTH) + 1) + "/"
                + calendar.get(Calendar.DAY_OF_MONTH) + "/";
        String fullPath = dirPath + folderPath;
        // 判断是否有文件夹，没有创建
        File folder = new File(fullPath);
        if (!folder.exists() && !folder.isDirectory()) {
            folder.mkdirs();
        }

        MultipartFile file = multiReq.getFile("file");
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.indexOf("."));
        String localFileName = new PufangUtils().getUuid() + suffix;
        File localFile = new File(dirPath + folderPath + localFileName);
        if (!localFile.exists()) {
            localFile.createNewFile();

            FileOutputStream fos = new FileOutputStream(
                    localFile);
            FileInputStream fs = (FileInputStream) multiReq.getFile("file").getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fs.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            fs.close();

        } else {
            logger.info("文件已存在！！");
        }

        map.put("url", folderPath + localFileName);

        return CommonResult.success(map);
    }
}
